import random
import threading
import time

from connection import PhoenixConnect

conn: PhoenixConnect

done = 0
index = 0

foo = ('2021-07-07', '2021-07-08', '2021-07-09', '2021-07-10', '2021-07-11', '2021-07-12', '2021-07-13', '2021-07-14')


def current_milli():
    return int(round(time.time() * 1000))


time_tuple = (current_milli() - 604800000, current_milli())


class DataCreator:
    conn = None
    cursor = None
    tid: int
    start: int
    end: int

    def __init__(self, url, tid, start, end):
        self.conn = PhoenixConnect(url)
        self.cursor = self.conn.get_update_cursor()
        self.tid = tid
        self.start = start
        self.end = end

    def exec_updates(self, sqls):
        try:
            for sql in sqls:
                # print(sql)
                self.cursor.execute(sql)
        except Exception as ex:
            print(ex)

    def select(self, sql):
        return self.conn.select(sql)

    # 为用户创建位置信息数据
    def create_data(self):
        global done
        global index
        print('Thread %d started...' % self.tid)

        try:
            for i in range(self.start, self.end + 1):
                sqls = []
                uid = i
                name = 'name_%d' % i
                next_count_date = random.choice(foo)
                sql = "UPSERT INTO GE.USER_GE(UID, NAME, STATUS, NEXT_COUNT_DATE) " \
                      "VALUES(%d, '%s', '%s', '%s')" % (uid, name, "NORMAL", next_count_date)
                sqls.append(sql)
                # 每个用户上传5-10个位置
                # 随机3个位置 每次从里面选取
                coorl_list = [
                    Coord(round(random.uniform(coord1.x, coord2.x), 6), round(random.uniform(coord2.y, coord1.y), 6)),
                    Coord(round(random.uniform(coord1.x, coord2.x), 6), round(random.uniform(coord2.y, coord1.y), 6)),
                    Coord(round(random.uniform(coord1.x, coord2.x), 6), round(random.uniform(coord2.y, coord1.y), 6))
                ]
                for j in range(1, random.randint(8, 10)):
                    index += 1
                    create_ts = random.uniform(time_tuple[0], time_tuple[1])
                    coord = random.choice(coorl_list)
                    sql = "UPSERT INTO GE.USER_POSITION(" \
                          "ID, UID, CREATE_TS, POSITION, CELL_ID) " \
                          "VALUES(%d, %d, %d, '%s', 0)" % (index, uid, create_ts, coord.get_value())

                    sqls.append(sql)

                # print(sqls)

                self.exec_updates(sqls)
        except Exception as ex:
            print('%d号线程异常：' % self.tid)
            print(ex)

        done = done + 1


class Coord(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_value(self):
        return '{\"x\": %f,\"y\": %f}' % (self.x, self.y)


# 范围为武汉市地图坐标（114.168256,30.731558） - （114.632225,30.337035）
coord1 = Coord(114.168256, 30.731558)
coord2 = Coord(114.632225, 30.337035)

if __name__ == '__main__':
    # 武汉地图大概50*50 km^2 可以初始化2500个格子
    # 假设平均每个格子20个人 需要创建50000个用户
    # 假设每个用户上传10次位置

    # 创建 50000 个用户位置信息
    url = 'http://mng1:8765/'

    dc1 = DataCreator(url, 1, 1, 50)
    # dc2 = DataCreator(url, 2, 10001, 20000)
    # dc3 = DataCreator(url, 3, 20001, 30000)
    # dc4 = DataCreator(url, 4, 30001, 40000)
    # dc5 = DataCreator(url, 5, 40001, 50000)

    t1 = threading.Thread(target=dc1.create_data, args=())
    # t2 = threading.Thread(target=dc2.create_data, args=())
    # t3 = threading.Thread(target=dc3.create_data, args=())
    # t4 = threading.Thread(target=dc4.create_data, args=())
    # t5 = threading.Thread(target=dc5.create_data, args=())

    t1.start()
    # t2.start()
    # t3.start()
    # t4.start()
    # t5.start()

    # while done < 5:
    #     print("index: %d" % index)
    #     time.sleep(1)
